package com.yoooya.base.utils.sms;

import java.io.ByteArrayInputStream;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.yoooya.base.utils.DateUtils;

/**
 * 
 * @author Sun Yijing<br />
 *         Copyright © Xiamen Yoooya NetWorks Co.,Ltd.
 * @since yoooya software platform v1.0.0
 * @version 1.0.0 <br />
 *          <table border="1" cellpadding="3" cellspacing="0">
 *          <tr>
 *          <th align="left" colspan="3"><b>修改历史</b></th>
 *          </tr>
 *          <tr>
 *          <td>修改日期</td>
 *          <td>修改人</td>
 *          <td>修改描述</td>
 *          </tr>
 *          <tr>
 *          <td>2018-6-20</td>
 *          <td>Sun Yijing</td>
 *          <td>新建</td>
 *          </tr>
 *          </table>
 */
@Component
public class UcpaasSmsUtils {
	@Value("${sms.ucpaas.softVersion}")
	private String softVersion = "2014-06-30";
	@Value("${sms.ucpaas.accountSid}")
	private String accountSid = "8869e0be250e8db9e92a33fae44a6fc0";
	@Value("${sms.ucpaas.appId}")
	private String appId = "e7b78f0086874169a3aabf38ae417c16";
	@Value("${sms.ucpaas.authToken}")
	private String authToken = "7837971c9afcbdf998d086d2fd7c76c5";
	@Value("${sms.ucpaas.server}")
	private String server = "api.ucpaas.com";

	public String templateSMS(String templateId, String to, String param) {
		// TODO Auto-generated method stub
		String result = "";
		DefaultHttpClient httpclient = getDefaultHttpClient();
		try {
			// MD5加密
			EncryptUtil encryptUtil = new EncryptUtil();
			// 构造请求URL内容
			String timestamp = DateUtils.format(new Date(), "yyyyMMddHHmmss");// 时间戳
			String signature = getSignature(accountSid, authToken, timestamp,
					encryptUtil);
			String url = getStringBuffer().append("/").append(softVersion)
					.append("/Accounts/").append(accountSid)
					.append("/Messages/templateSMS").append("?sig=")
					.append(signature).toString();
			TemplateSMS templateSMS = new TemplateSMS();
			templateSMS.setAppId(appId);
			templateSMS.setTemplateId(templateId);
			templateSMS.setTo(to);
			templateSMS.setParam(param);

			String body = JSON.toJSONString(templateSMS);
			body = "{\"templateSMS\":" + body + "}";
			HttpResponse response = requestPost("application/json", accountSid,
					authToken, timestamp, url, httpclient, encryptUtil, body);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}
			EntityUtils.consume(entity);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接
			httpclient.getConnectionManager().shutdown();
		}
		return result;
	}

	public HttpResponse requestPost(String cType, String accountSid,
			String authToken, String timestamp, String url,
			DefaultHttpClient httpclient, EncryptUtil encryptUtil, String body)
			throws Exception {
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader("Accept", cType);
		httppost.setHeader("Content-Type", cType + ";charset=utf-8");
		String src = accountSid + ":" + timestamp;
		String auth = encryptUtil.base64Encoder(src);
		httppost.setHeader("Authorization", auth);
		BasicHttpEntity requestBody = new BasicHttpEntity();
		requestBody
				.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
		requestBody.setContentLength(body.getBytes("UTF-8").length);
		httppost.setEntity(requestBody);
		// 执行客户端请求
		HttpResponse response = httpclient.execute(httppost);
		return response;
	}

	public DefaultHttpClient getDefaultHttpClient() {
		DefaultHttpClient httpclient = null;
		httpclient = new DefaultHttpClient();
		return httpclient;
	}

	public StringBuffer getStringBuffer() {
		StringBuffer sb = new StringBuffer("https://");
		sb.append(server);
		return sb;
	}

	public String getSignature(String accountSid, String authToken,
			String timestamp, EncryptUtil encryptUtil) throws Exception {
		String sig = accountSid + authToken + timestamp;
		String signature = encryptUtil.md5Digest(sig);
		return signature;
	}

}
